namespace DotNetNuke.Services.Cache.BroadcastPollingCachingProvider
{
    using DotNetNuke.Common.Utilities;
    using DotNetNuke.Services.Cache.BroadcastPollingCachingProvider.Data;
    using System;
    using System.Collections;
    using System.Data;
    using System.IO;
    using System.Runtime.CompilerServices;
    using System.Text;
    using System.Xml.Serialization;

    public class Controller
    {
        public int AddBroadcast(string BroadcastType, string BroadcastMessage, string ServerName)
        {
            return DataProvider.Instance().AddBroadcast(BroadcastType, BroadcastMessage, ServerName);
        }

        public void AddCachedObject(string Key, object obj, string ServerName)
        {
            if (obj != null)
            {
                string str = this.Serialize((obj));
                DataProvider.Instance().AddCachedObject(Key, str, ServerName);
            }
        }

        public void DeleteCachedObject(string Key)
        {
            DataProvider.Instance().DeleteCachedObject(Key);
        }

        private object Deserialize(string str, Type objType)
        {
            MemoryStream objStream = new MemoryStream(Encoding.Default.GetBytes(str));
            XmlSerializer serializer = new XmlSerializer(objType);
            TextReader tr = new StreamReader(objStream);
            return (serializer.Deserialize(tr));
        }

        public ArrayList GetBroadcasts(string ServerName)
        {
            return CBO.FillCollection(DataProvider.Instance().GetBroadcasts(ServerName), typeof(BroadcastInfo));
        }

        public object GetCachedObject(string Key, Type objType)
        {
            object GetCachedObject;
            IDataReader dr = DataProvider.Instance().GetCachedObject(Key);
            try
            {
                object obj = null;
                if (dr != null)
                {
                    while (dr.Read())
                    {
                        string str = Convert.ToString((dr["CachedObjectValue"]));
                        obj = (this.Deserialize(str, objType));
                    }
                }
                GetCachedObject = obj;
            }
            finally
            {
                if (dr != null)
                {
                    dr.Close();
                }
            }
            return GetCachedObject;
        }

        private string Serialize(object obj)
        {
            return XmlUtils.Serialize((obj));
        }
    }
}

